const fs = require('fs');
const {pathResolve} = require('./utils');

class FileFun {
  constructor(path) {
    this.path = path;
  }

  /**
   * 读取文件列表显示页面的左边的菜单
   * @returns {Promise<unknown>}
   */
  readFileList() {
    const arr = [];
    return new Promise(s => {
      fs.readdir(this.path, async (err, data) => {
        if (err) {
          console.log('读取文件列表错误');
          console.log(err);
          s(null);
          return;
        }
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          if (!item.includes('.txt')) {
            continue;
          }
          const path = pathResolve(this.path, item);
          const content = await this.readFileToTenLength(path);
          arr.push({
            path,
            content
          });
        }
        s(arr);
      });
    });
  }

  /**
   * 读取指定文件前10个文字
   * @param path 文件的路径
   * @returns {Promise<unknown>}
   */
  readFileToTenLength(path) {
    return new Promise(s => {
      fs.open(path, 'r', function (err, fd) {
        if (err) {
          throw err;
        }
        const buffer = new Buffer.alloc(400);
        // 读取文件
        fs.read(fd, buffer, 0, 400, 0, function (err, bytesRead, buffer) {
          if (err) {
            console.log('read fail');
            console.log(err);
          }
          let data = buffer.slice(0, bytesRead).toString();
          data = data.replace(/<[^>]+>/g, '');
          data = data.substr(0, 10);
          // 关闭文件
          fs.close(fd, function (err) {
            if (err) {
              console.log(err);
            }
            s(data);
          });
        });
      });
    });
  }

  /**
   * 存储内容到文件
   * @param path 文件的路径
   * @param content 文件的内容
   * @returns {Promise<unknown>}
   */
  writeFile(path, content) {
    return new Promise(s => {
      fs.writeFile(path, content, {encoding: 'UTF-8'}, function (err) {
        if (err) {
          console.log('保存文件失败');
          s(null);
          return;
        }
        console.log('保存文件成功');
        s(true);
      });
    });
  }

  /**
   * 读取指定文件的内容
   * @param path
   * @returns {Promise<unknown>}
   */
  readFile(path) {
    return new Promise(s => {
      fs.readFile(path, 'utf-8', function (err, data) {
        if (err) {
          console.log('读取文件失败');
          console.log(err);
          s(null);
          return;
        }
        console.log('读取文件成功');
        console.log(data);
        s(data);
      });
    });
  }
}

function getState(path) {
  return new Promise((resolve, reject) => {
    fs.stat(path, (err, stats) => {
      if (err) {
        resolve(false);
      } else {
        resolve(stats);
      }
    });
  });
}

// async function main() {
//     console.log(localGitStorePath);
//     const fileFun = new FileFun(localGitStorePath);
//     const data = await fileFun.readFileList();
//     console.log(data);
// }
//
// main();
FileFun.getState = getState;
module.exports = FileFun;
